// 简化的数据库服务，使用localStorage作为存储

// 数据库集合名称常量
export const COLLECTIONS = {
  USERS: 'users',
  VIDEOS: 'videos',
  COMMENTS: 'comments',
  TAGS: 'tags',
  TOPICS: 'topics',
  ACTIVITIES: 'activities',
  ANIMES: 'animes',
  CATEGORIES: 'categories'
}

// 简化的数据库服务类
class SimpleDbService {
  constructor() {
    this.storageKeyPrefix = 'bilibili_clone_'
    this.ensureCollections()
  }

  // 确保集合存在
  ensureCollections() {
    Object.values(COLLECTIONS).forEach(collection => {
      const key = this.getStorageKey(collection)
      if (!localStorage.getItem(key)) {
        localStorage.setItem(key, JSON.stringify([]))
      }
    })
  }

  // 获取存储键名
  getStorageKey(collection) {
    return `${this.storageKeyPrefix}${collection}`
  }

  // 获取集合数据
  getCollection(collectionName) {
    try {
      const key = this.getStorageKey(collectionName)
      const data = localStorage.getItem(key)
      return data ? JSON.parse(data) : []
    } catch (error) {
      console.error(`获取${collectionName}数据失败:`, error)
      return []
    }
  }

  // 获取单个文档
  getDocument(collectionName, id) {
    const collection = this.getCollection(collectionName)
    return collection.find(item => item.id === id) || null
  }

  // 添加文档
  addDocument(collectionName, data) {
    try {
      const collection = this.getCollection(collectionName)
      const newDocument = {
        ...data,
        id: data.id || this.generateId(),
        createdAt: data.createdAt || new Date().toISOString()
      }
      collection.push(newDocument)
      this.saveCollection(collectionName, collection)
      return newDocument
    } catch (error) {
      console.error(`添加文档失败:`, error)
      throw error
    }
  }

  // 更新文档
  updateDocument(collectionName, id, data) {
    try {
      const collection = this.getCollection(collectionName)
      const index = collection.findIndex(item => item.id === id)
      if (index === -1) {
        throw new Error(`文档不存在: ${id}`)
      }
      collection[index] = {
        ...collection[index],
        ...data,
        updatedAt: new Date().toISOString()
      }
      this.saveCollection(collectionName, collection)
      return collection[index]
    } catch (error) {
      console.error(`更新文档失败:`, error)
      throw error
    }
  }

  // 删除文档
  deleteDocument(collectionName, id) {
    try {
      const collection = this.getCollection(collectionName)
      const filteredCollection = collection.filter(item => item.id !== id)
      this.saveCollection(collectionName, filteredCollection)
      return true
    } catch (error) {
      console.error(`删除文档失败:`, error)
      throw error
    }
  }

  // 清空集合
  clearCollection(collectionName) {
    try {
      localStorage.setItem(this.getStorageKey(collectionName), JSON.stringify([]))
      return true
    } catch (error) {
      console.error(`清空集合失败:`, error)
      throw error
    }
  }

  // 保存集合数据
  saveCollection(collectionName, data) {
    try {
      localStorage.setItem(this.getStorageKey(collectionName), JSON.stringify(data))
    } catch (error) {
      console.error(`保存${collectionName}数据失败:`, error)
      throw error
    }
  }

  // 生成唯一ID
  generateId() {
    return Date.now().toString(36) + Math.random().toString(36).substr(2)
  }

  // 简单查询
  queryDocuments(collectionName, field, operator, value) {
    const collection = this.getCollection(collectionName)
    return collection.filter(item => {
      const itemValue = item[field]
      switch (operator) {
        case '==':
          return itemValue === value
        case '!=':
          return itemValue !== value
        case '>':
          return itemValue > value
        case '<':
          return itemValue < value
        case '>=':
          return itemValue >= value
        case '<=':
          return itemValue <= value
        case 'contains':
          return itemValue && itemValue.includes(value)
        default:
          return true
      }
    })
  }

  // 批量添加文档
  batchAddDocuments(collectionName, documents) {
    try {
      const collection = this.getCollection(collectionName)
      const newDocuments = documents.map(doc => ({
        ...doc,
        id: doc.id || this.generateId(),
        createdAt: doc.createdAt || new Date().toISOString()
      }))
      collection.push(...newDocuments)
      this.saveCollection(collectionName, collection)
      return newDocuments
    } catch (error) {
      console.error(`批量添加文档失败:`, error)
      throw error
    }
  }

  // 获取集合大小
  getCollectionSize(collectionName) {
    const collection = this.getCollection(collectionName)
    return collection.length
  }
}

// 创建单例实例
const dbService = new SimpleDbService()

// 业务数据服务
export const dataService = {
  users: {
    getAll: () => dbService.getCollection(COLLECTIONS.USERS),
    getById: (id) => dbService.getDocument(COLLECTIONS.USERS, id),
    create: (userData) => dbService.addDocument(COLLECTIONS.USERS, userData),
    update: (id, userData) => dbService.updateDocument(COLLECTIONS.USERS, id, userData),
    delete: (id) => dbService.deleteDocument(COLLECTIONS.USERS, id),
    findByUsername: (username) => dbService.queryDocuments(COLLECTIONS.USERS, 'username', '==', username)[0] || null,
    findByEmail: (email) => dbService.queryDocuments(COLLECTIONS.USERS, 'email', '==', email)[0] || null
  },
  videos: {
    getAll: () => dbService.getCollection(COLLECTIONS.VIDEOS),
    getById: (id) => dbService.getDocument(COLLECTIONS.VIDEOS, id),
    create: (videoData) => dbService.addDocument(COLLECTIONS.VIDEOS, videoData),
    update: (id, videoData) => dbService.updateDocument(COLLECTIONS.VIDEOS, id, videoData),
    delete: (id) => dbService.deleteDocument(COLLECTIONS.VIDEOS, id),
    getByCategory: (category) => dbService.queryDocuments(COLLECTIONS.VIDEOS, 'category', '==', category),
    getRecommended: () => dbService.queryDocuments(COLLECTIONS.VIDEOS, 'isRecommended', '==', true)
  },
  tags: {
    getAll: () => dbService.getCollection(COLLECTIONS.TAGS),
    create: (tagData) => dbService.addDocument(COLLECTIONS.TAGS, tagData),
    delete: (id) => dbService.deleteDocument(COLLECTIONS.TAGS, id)
  },
  topics: {
    getAll: () => dbService.getCollection(COLLECTIONS.TOPICS),
    getById: (id) => dbService.getDocument(COLLECTIONS.TOPICS, id),
    create: (topicData) => dbService.addDocument(COLLECTIONS.TOPICS, topicData)
  },
  activities: {
    getAll: () => dbService.getCollection(COLLECTIONS.ACTIVITIES),
    getById: (id) => dbService.getDocument(COLLECTIONS.ACTIVITIES, id)
  },
  animes: {
    getAll: () => dbService.getCollection(COLLECTIONS.ANIMES),
    getById: (id) => dbService.getDocument(COLLECTIONS.ANIMES, id),
    getNew: () => dbService.queryDocuments(COLLECTIONS.ANIMES, 'isNew', '==', true)
  },
  categories: {
    getAll: () => dbService.getCollection(COLLECTIONS.CATEGORIES),
    getById: (id) => dbService.getDocument(COLLECTIONS.CATEGORIES, id)
  },
  comments: {
    getAll: () => dbService.getCollection(COLLECTIONS.COMMENTS),
    create: (commentData) => dbService.addDocument(COLLECTIONS.COMMENTS, commentData),
    getByVideoId: (videoId) => dbService.queryDocuments(COLLECTIONS.COMMENTS, 'videoId', '==', videoId)
  }
}

// Vue插件
export const DatabasePlugin = {
  install(app) {
    app.config.globalProperties.$db = dbService
    app.config.globalProperties.$data = dataService
    app.provide('$db', dbService)
    app.provide('$data', dataService)
  }
}

// 导出数据库服务
export { dbService }
export default dbService